package com.quectel.util.classpath;

import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 拷贝classpath下的文件
 *
 * @author: caolu
 * @email: louis.cao@quectel.com
 * @date: 2023-08-17 19:31:00
 */
@Slf4j
public class ClasspathUtils {

    /**
     * @param destPath  目录例如 /root/lib/test
     * @param resources static/code.json
     */
    public static void copyFiles(String destPath, String... resources) {

        copyFiles(destPath, true, resources);
    }

    /**
     * @param destPath      目录例如 /root/lib/test
     * @param forceOverride true:文件存在则覆盖 false:文件存在则跳过
     * @param resources     static/code.json
     */
    public static void copyFiles(String destPath, boolean forceOverride, String... resources) {

        Preconditions.checkNotNull(destPath);
        Preconditions.checkArgument(resources != null && resources.length > 0);

        File file = new File(destPath);
        Preconditions.checkArgument(!file.exists() || file.isDirectory(), "Copy classpath file dest path error");
        if (!file.exists()) {
            // 级联创建文件夹
            boolean mkdirs = file.mkdirs();
            Preconditions.checkArgument(mkdirs, "Copy classpath file mkdirs error");
        }

        for (String resource : resources) {
            String fileName = resource;
            if (resource.contains("/")) {
                fileName = resource.substring(resource.lastIndexOf("/") + 1);
            }
            try (
                    InputStream in = ClasspathUtils.class.getClassLoader().getResourceAsStream(resource);

            ) {
                if (in != null) {
                    File destFile = new File(destPath, fileName);
                    if (forceOverride) {
                        // 强制覆盖 文件存在则删除
                        if (destFile.exists()) {
                            boolean deleted = destFile.delete();
                            Preconditions.checkArgument(deleted, "Delete file failed for force override");
                        }
                    } else {
                        // 不强制覆盖
                        if (destFile.exists()) {
                            // 文件存在则跳过
                            continue;
                        }
                    }
                    try (OutputStream os = new FileOutputStream(destFile)) {
                        IOUtils.copy(in, os);
                    } catch (Exception e) {
                        log.warn("The classpath file{}not copy to the dest path", resource);
                    }
                }
            } catch (Exception e) {
                log.warn("The classpath file{}not copy to the dest path", resource);
            }
        }
    }
}
